package com.server.llh.llhserverwork.activity.my;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.family.llh.lelaohuitoastview.dialog.toast.T;
import com.google.gson.Gson;
import com.lelaohui.net.listener.NetDataListener;
import com.lelaohui.net.netmanager.INetRequestManager;
import com.lelaohui.net.netmanager.NetRequestManager;
import com.lelaohui.net.request.LRequest;
import com.lelaohui.net.utils.UrlsTools;
import com.llh.llhsuppliers.R;
import com.server.llh.llhserverwork.activity.base.LlhBaseNFCActivity;
import com.server.llh.llhserverwork.app.LelaohuirelativesApp;
import com.server.llh.llhserverwork.bean.AdminInfo;
import com.server.llh.llhserverwork.bean.Constants;
import com.server.llh.llhserverwork.bean.LoginInfoBean;
import com.server.llh.llhserverwork.receiver.GetCardBroadCast;
import com.server.llh.llhserverwork.utils.Constant;
import com.server.llh.llhserverwork.utils.Md5;
import com.server.llh.llhserverwork.utils.ServerPort;
import com.server.llh.llhserverwork.utils.SharedPreferenceUtil;
import com.server.llh.llhserverwork.view.AlertDialog;
import com.server.llh.llhserverwork.view.CleanableEditText;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by ZTF on 2017-06-06.
 * 登陆
 */

public class LoginActivity extends LlhBaseNFCActivity {
    private static final String TAG = "LoginActivity";
    @BindView(R.id.titleName)
    TextView titleName;
    @BindView(R.id.main_back)
    ImageButton mainBack;
    @BindView(R.id.leftBtn_RL_title_base)
    RelativeLayout leftBtnRLTitleBase;
    @BindView(R.id.serverName)
    TextView serverName;
    @BindView(R.id.linearLayout1)
    LinearLayout linearLayout1;
    @BindView(R.id.image_log)
    ImageView imageLog;
    @BindView(R.id.userName)
    CleanableEditText userNameE;
    @BindView(R.id.userPwd)
    CleanableEditText userPwd;
    @BindView(R.id.userlogin)
    LinearLayout userlogin;
    @BindView(R.id.btn_login)
    TextView btnLogin;
    @BindView(R.id.version)
    TextView version;
    GetCardBroadCast getCardBroadCast = null;
    private boolean logBtn = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

        titleName.setText("登陆");
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.READ_CARDACTION);
        getCardBroadCast = new GetCardBroadCast();
        getCardBroadCast.setmHandler(handler);
        getLbm().registerReceiver(getCardBroadCast, filter);
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == -1000) {
                String cardId = String.valueOf(msg.obj);
                userNameE.setText("" + cardId);
//                reqLogin(Long.valueOf(cardId),"","");
            }
        }
    };


    @Override
    public void showProgress() {
        try {
            showProgress(LoginActivity.this);
        } catch (Exception E) {

        }
    }

    @Override
    protected INetRequestManager getRequestManager() {
        return NetRequestManager.getInstance();
    }

    @Override
    public void hideProgress() {
        try {
            closeProgress();
        } catch (Exception E) {

        }
    }

    @Override
    protected int getlayout() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void doBasess() {

    }


    @OnClick({R.id.main_back, R.id.btn_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.main_back:
                showInfo();
                break;
            case R.id.btn_login:
                if (logBtn == false) {
                    userlogin.setVisibility(View.VISIBLE);
                    imageLog.setVisibility(View.GONE);
                    String userNameStr = userNameE.getText().toString();
                    String pwdStr = userPwd.getText().toString();
                    if (TextUtils.isEmpty(userNameStr) || userNameStr.equals("")) {
                        T.showAnimToast(getApplicationContext(), "请输入用户名或刷卡登陆");
                        return;
                    }
                    if (TextUtils.isEmpty(pwdStr) || pwdStr.equals("")) {
                        T.showAnimToast(getApplicationContext(), "请输入密码或刷卡登陆");
                        return;
                    }
                    reqSupLogin(userNameStr, pwdStr);
                }
                break;
        }
    }

    private void reqSupLogin(String loginPhone, String loginPassword) {
        LRequest lRequest = new LRequest();
        lRequest.addParam("user", loginPhone);
        lRequest.addParam("password", loginPassword);
        lRequest.addParam("channel", 6);
        lRequest.setUriType(UrlsTools.ADMIN_REQ);
        lRequest.setUri(ServerPort.USER_LOGIN);
        lRequest.setReqType("");
        lRequest.setType(String.class);
        requestData(lRequest, new NetDataListener<String>() {
            @Override
            public void onError(Throwable t) {
                T.showAnimErrorToast(getApplicationContext(), "服务器繁忙!");
            }

            @Override
            public void onNext(String responseBean, String code) {
                Log.d(TAG, "dataBean ==" + responseBean.toString() + "code==" + code);
                if ("0".equals(responseBean)) {
                    Log.d(TAG, "dataBean ==" + responseBean.toString());
                    saveUserInfo(Constants.UserInfo.TOKEN_STR, code);
                    reqLogin(code);
                } else {
                    T.showAnimToast(getApplicationContext(), "用户名或密码输入错误或一个人不能有多个机构！");
                }
            }
        });
    }

    private AdminInfo loginInfoBean;
    public static Map<String, String> waiterOrgList = new HashMap<>();

    private void reqLogin(String token) {
        LRequest lRequest = new LRequest();
        lRequest.addParam("token", token);
        lRequest.setUri(ServerPort.GET_USER_LOGIN);
        lRequest.setReqType("");
        lRequest.setUriType(UrlsTools.ADMIN_REQ);
        lRequest.setType(String.class);
        requestData(lRequest, new NetDataListener<String>() {
            @Override
            public void onError(Throwable t) {
                T.showAnimErrorToast(getApplicationContext(), "服务器繁忙!");
            }

            @Override
            public void onNext(String responseBean, String code) {
                if (responseBean != null) {
                    Log.d(TAG, "responseBean==" + responseBean);
                    loginInfoBean = new Gson().fromJson(responseBean, AdminInfo.class);
                    AdminInfo.DataBean dataBeana = loginInfoBean.getData();
                    if (dataBeana != null) {
                        AdminInfo.DataBean.AdminInfoBean dataBean = dataBeana.getAdminInfo();
                        if (dataBean != null) {
                            saveUserInfo(Constants.UserInfo.USER_ID, dataBean.getUserId());
                            if (TextUtils.isEmpty(dataBean.getUserName())) {
                                saveUserInfo(Constants.UserInfo.USER_NAMW, "");
                            } else {
                                saveUserInfo(Constants.UserInfo.USER_NAMW, dataBean.getUserName() + "");
                            }
                            Log.d(TAG, "dataBean.getAdminOrgId()==" + dataBean.getAdminOrgId());
                            saveUserInfo(Constants.UserInfo.ORG_ID, dataBean.getAdminOrgId() + "");
                            saveUserInfo(Constants.UserInfo.ORG_TYPE, dataBean.getAdminOrgType() + "");
                            saveUserInfo(Constants.UserInfo.ORG_NAME, dataBean.getAdminOrgName() + "");
                            saveUserInfo(Constants.UserInfo.CHAIN_NAME, dataBean.getChainName() + "");
                            saveUserInfo(Constants.UserInfo.CHAIN_ID, dataBean.getChainId() + "");
                            Intent intent = new Intent(getApplicationContext(), MainTabActivity.class);
                            startActivity(intent);
                            finish();
                        }
                    }
                } else {
                    T.showAnimToast(getApplicationContext(), "用户名或密码输入错误或一个人不能有多个机构！");
                }
            }
        });
    }

    public void saveUserInfo(String key, Object value) {
        SharedPreferenceUtil.saveUserInfo(key, value, getApplicationContext());
    }

    private long firstTime = 0;

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (event.getAction() == KeyEvent.ACTION_DOWN
                    && event.getRepeatCount() == 0) {
                long secondTime = System.currentTimeMillis();
                if (secondTime - firstTime > 2000) {
                    firstTime = secondTime;
                    return true;
                } else {
                    showInfo();
                }
                return true;
            }
        }
        return super.dispatchKeyEvent(event);
    }

    private void showInfo() {
        AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
        builder.setTitle("温馨提示");
        builder.setMessage("\n" + "您确定要退出应用么？" + "\n");
        builder.setNegativeButton("取消", null);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                LelaohuirelativesApp.exit();
                System.exit(0);
                finish();
                dialog.cancel();
            }
        });
        builder.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (getCardBroadCast != null) {
            getLbm().unregisterReceiver(getCardBroadCast);
        }
    }
}
